package cn.lili.controller.feign.member;

import cn.hutool.core.collection.CollUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.CityDistribution;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.UserInfoDTO;
import cn.lili.modules.member.entity.dto.UserLoginDTO;
import cn.lili.modules.member.entity.dto.UserSearchParams;
import cn.lili.modules.member.entity.vo.UserVO;
import cn.lili.modules.member.service.CityDistributionService;
import cn.lili.modules.member.service.UserSecurityService;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.system.client.IRegionClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员 feign client
 *
 * @author Chopper
 * @version v1.0 2021-11-17 18:06
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class UserFeignController implements UserClient {

    private final UserService userService;

    private final UserSecurityService userSecurityService;

    private final IRegionClient regionClient;

    private final CityDistributionService cityDistributionService;

    @Override
    public User getById(String id) {
        return userService.getById(id);
    }

    @Override
    public User getByMobile(String mobile, SceneEnums scene) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMobile, mobile);
        queryWrapper.eq(User::getScene, scene.name());
        return userService.getOne(queryWrapper, false);
    }

    /**
     * 获取指定会员数据
     *
     * @param columns   指定获取的列
     * @param memberIds 会员ids
     * @return 指定会员数据
     */
    @Override
    public List<Map<String, Object>> listFieldsByMemberIds(String columns, List<String> memberIds) {
        return userService.listFieldsByMemberIds(columns, memberIds);
    }

    /**
     * 获取所有会员的手机号
     *
     * @return 所有会员的手机号
     */
    @Override
    public List<String> getAllMemberMobile() {
        //        TODO 这里需要重新实现
        return userService.getMemberMobile(new PageVO());
    }

    /**
     * 根据条件查询会员总数
     *
     * @param userSearchParams
     * @return 会员总数
     */
    @Override
    public long getUserNum(UserSearchParams userSearchParams) {
        return userService.getMemberNum(userSearchParams);
    }

    /**
     * 根据条件查询会员列表
     *
     * @param searchParams 查询参数
     * @return 会员列表
     */
    @Override
    public List<User> list(UserSearchParams searchParams) {
        return userService.list(searchParams);
    }


    /**
     * 更新会员登录时间为最新时间
     *
     * @param userId 会员id
     * @return 是否更新成功
     */
    @Override
    public Boolean updateUserLoginTime(String userId) {
        return userService.updateUserLoginTime(userId);
    }


    @Override
    public User queryUser(UserLoginDTO userLoginDTO) {
        return userService.userLoginQuery(userLoginDTO);
    }

    @Override
    public User mobilePhoneLogin(String mobile, SceneEnums scene) {
        return userService.mobilePhoneLogin(mobile, scene);
    }

    @Override
    public User register(UserInfoDTO userInfoDTO) {
        return userService.registerHandler(userInfoDTO);
    }

    @Override
    public void resetPasswordSign(String uuid, String mobile, SceneEnums scene) {
        userSecurityService.resetPasswordSign(uuid, mobile, scene);
    }

    @Override
    public Boolean resetPasswordByMobile(String uuid, String password, SceneEnums scene) {
        return userSecurityService.resetPasswordByMobile(uuid, password, scene);
    }

    @Override
    public UserVO info() {
        return userService.userInfo();
    }

    /**
     * 生成用户
     *
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public User generateUser(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenId, user.getOpenId());
        queryWrapper.eq(User::getScene, user.getScene());
        if (userService.count(queryWrapper) > 0) {
            throw new ServiceException("此飞语用户已存在，会员");
        }
        userService.save(user);
        return user;
    }

    @Override
    public User getByExtId(String extId) {
        return userService.getByExtId(extId);
    }

    @Override
    public User getByExtId2(String extId) {
        return userService.getByExtId2(extId);
    }

    @Override
    public User getByOpenId(String openId, String scene) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getOpenId, openId);
        userLambdaQueryWrapper.eq(User::getScene, scene);
        userLambdaQueryWrapper.last("limit 1");
        return userService.getOne(userLambdaQueryWrapper);
    }

    @Override
    public User getByUserName(String account, String scene) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, account);
        userLambdaQueryWrapper.eq(User::getScene, scene);
        userLambdaQueryWrapper.eq(User::getDeleteFlag, Boolean.FALSE);
        userLambdaQueryWrapper.last("limit 1");
        User user = userService.getOne(userLambdaQueryWrapper);
        return user;
    }

    @Override
    public Boolean deleteUserByExtId(String extId) {
       return userService.deleteUserByExtId(extId);
    }

    @Override
    public Boolean userFrozen(String userId, Boolean frozen) {
        User user = new User();
        user.setId(userId);
        user.setGreenFrozen(frozen);
        return userService.updateById(user);
    }

    @Override
    public String getOpenIdByFy() {
        return userService.getOpenIdByFy();
    }

    @Override
    public Boolean updateFyById(String openId, String account, String nickName, String userId, String scene) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        //普通会员使用的是id，店铺和供应商和城市站点使用的是extendId字段;
        if (!SceneEnums.MEMBER.name().equals(scene) && !SceneEnums.MANAGER.name().equals(scene) && !SceneEnums.URBAN_SUBSTATION.name().equals(scene)) {
            updateWrapper.eq(User::getExtendId, userId);
        } else {
            updateWrapper.eq(User::getId, userId);
        }
        updateWrapper.set(User::getOpenId, openId);
        updateWrapper.set(User::getAccount, account);
        updateWrapper.set(User::getFyName, nickName);
        updateWrapper.last("limit 1");
        return userService.update(updateWrapper);
    }

    @Override
    public List<User> selectUserListByIds(List<String> userIdList) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.in(User::getId, userIdList);
        userLambdaQueryWrapper.eq(User::getDeleteFlag, Boolean.FALSE);
        return userService.list(userLambdaQueryWrapper);
    }


    /**
     * 更新头像和昵称
     * @param user
     * @return
     */
    @Override
    public Boolean updateUserFyNameAndFaceById(User user) {
        return userService.updateById(user);
    }

    @Override
    public Boolean updateById(User user) {
        return userService.updateById(user);
    }

    /**
     * 根据用户id查找上级数量
     *
     * @param userIds
     * @return
     */
    @Override
    public Map<String, Integer> selectUserChildCountByUserIds(List<String> userIds) {
        return userService.selectUserChildCountByUserIds(userIds);
    }


    /**
     * 根据店主用户ids查询下级id
     * @param userIds
     * @return Map<String, List<String>> 店主id,下级id集合
     */
    @Override
    public Map<String, List<String>> selectChildUserIdsByMemberIds(List<String> userIds) {
        return userService.selectChildUserIdsByMemberIds(userIds);
    }

    /**
     * 清除邀请人id
     * @param user
     * @return
     */
    @Override
    public Boolean removeChildUserRelationship(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.select(User::getId);
        wrapper.eq(User::getParentId, user.getParentId());
        //获取下级id
        List<User> childUsers = userService.list(wrapper);
        if(CollUtil.isNotEmpty(childUsers)){
            //转成map
            List<String> userids = childUsers.stream().map(User::getId).collect(Collectors.toList());
            //根据id清空user表中上级信息
            LambdaUpdateWrapper<User> update = new LambdaUpdateWrapper();
            update.in(User::getId,userids);
            update.set(User::getParentId, "");
            update.set(User::getParentUsername, "");
            //去掉店长标识
            update.set(User::getIsDistribution, Boolean.FALSE);
            return userService.update(update);
        }
        return false;
    }

    /**
     * 根据id获取下级，与下级的下级
     * @param currentId id
     * @return
     */
    @Override
    public String callGetSubordinatesAndSubSubordinates(String currentId) {
        return userService.callGetSubordinatesAndSubSubordinates(currentId);
    }

    /**
     * 根据ID获取下级直推用户
     *
     * @param userId 父级ID
     * @return 用户列表
     */
    @Override
    public List<User> getLowerByParentId(String userId) {
        return userService.getLowerByParentId(userId);
    }

    /**
     * 当前区域城主
     *
     * @param regionId 当前区域城主
     * @return 当前区域城主
     */
    @Override
    public CityDistribution getCastellan(String regionId) {
        CityDistribution query = new CityDistribution();
        query.setDistrictCode(regionId);
        return cityDistributionService.getCastellan(query);
    }

    @Override
    public Page<CityDistribution> historyEarnings(Integer page, Integer size) {
        return cityDistributionService.historyEarnings(new Page<>(page, size));
    }

    /**
     * 根据区域，年月获取城主
     * @param regionId 区域
     * @param year 年
     * @param month 月
     * @return 城主
     */
    @Override
    public CityDistribution getCastellanByCodeYearMonth(String regionId, Integer year, Integer month) {
        return cityDistributionService.getCastellanByCodeYearMonth(regionId, year, month);
    }

    @Override
    public Boolean updateUserByIdAndMember(User user) {
        //同步账户信息
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, user.getId());
        updateWrapper.eq(User::getScene, SceneEnums.MEMBER.name());
        if (StringUtils.isNotEmpty(user.getUsername())) {
            updateWrapper.set(User::getUsername, user.getUsername());
        }
        if (StringUtils.isNotEmpty(user.getAccount())) {
            updateWrapper.set(User::getAccount, user.getAccount());
        }
        if (StringUtils.isNotEmpty(user.getNickName())) {
            updateWrapper.set(User::getNickName, user.getNickName());
        }
        if (StringUtils.isNotEmpty(user.getFace())) {
            updateWrapper.set(User::getFace, user.getFace());
        }
        return userService.update(updateWrapper);
    }

    @Override
    public List<User> getListByFiledValue(String filed, String filedValue) {
        QueryWrapper<User> userLambdaQueryWrapper = new QueryWrapper<>();
        userLambdaQueryWrapper.like(filed, filedValue);
        return userService.list(userLambdaQueryWrapper);
    }
}
